<template>
  <div class="accounts" style="padding: 15px; box-sizing: border-box" v-loading="loading">
    <!-- 图 -->
    <!-- <div v-for="(item, index) in items" :key="index" style="display: flex">
      <div
        v-for="(ele, index) in item"
        :key="index"
        style="background: pink; margin: 1px; width: 40px; text-align: center"
        @click="kankan(ele.num)"
      >
        {{ ele.num }}{{ ele.name ? ele.coll + "." + ele.row : "" }}
      </div>
    </div> -->
    <!-- 头部  -->
    <VolHeader icon="md-apps" text="应收帐户" style="color: red">
      <div class="accounts_header">
        <el-input v-model="params.accName" placeholder="请输入应收账户名称"></el-input>
        <Button class="search_left" type="info" icon="md-search" @click="searchClick">查询</Button>
        <Button class="search_right" type="info" icon="el-icon-search" @click="moreClick">
          <Icon type="ios-arrow-down"></Icon>
        </Button>
        <Button type="success" icon="md-refresh" @click="refreshClick">刷新</Button>
        <Button type="error" icon="md-add" @click="addClick()">新建</Button>
        <Button type="warning" icon="md-close" @click="deleteClick()">删除</Button>
        <Button type="primary" @click="ExportCampsPeopleBatcl">导出</Button>
      </div>
    </VolHeader>
    <div class="accounts_table">
      <!-- 高级查询弹窗 -->
      <div class="search_box" v-show="searchBoxShow">
        <el-form :model="params" label-width="120px">
          <div class="search_form">
            <el-form-item label="应收账户名称：">
              <el-input v-model="params.accName" placeholder="请输入应收帐户名称"></el-input>
            </el-form-item>
            <el-form-item label="应收账户编号：">
              <el-input v-model="params.accCode" placeholder="请输入应收帐户编号"></el-input>
            </el-form-item>
            <el-form-item label="联系人姓名：">
              <el-input v-model="params.customer" placeholder="请输入联系人姓名"></el-input>
            </el-form-item>
          </div>
          <div class="search_form">
            <el-form-item label="联系人电话：">
              <el-input v-model="params.phone" placeholder="请输入联系人电话"></el-input>
            </el-form-item>
            <el-form-item label="状态：">
              <el-select v-model="params.isvalid" placeholder="请选择账户状态">
                <el-option label="有效" value="1"></el-option>
                <el-option label="无效" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label=""> </el-form-item>
          </div>
          <div class="search_btn">
            <Button type="info" ghost @click="searchClick">
              <Icon type="md-search" />查询
            </Button>

            <Button type="success" ghost @click="resetSearch">
              <Icon type="md-refresh" />重置
            </Button>
            <Button type="warning" ghost @click="searchBoxShow = !searchBoxShow">
              <Icon type="md-power" />关闭
            </Button>
          </div>
        </el-form>
      </div>
      <div class="content">
        <!-- 表格  -->
        <VolTable ref="table" :height="tableHeight" :loadKey="true" :columns="columns" :ck="true"
          :pagination-hide="true" :index="true" :summary="true" :single="false"
          :tableData="tableData" :columnIndex="false" @rowClick="rowClick" :isPaging="true">
        </VolTable>
      </div>
      <!-- 分页  -->
    </div>
    <div class="paginat">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage" :page-sizes="[30, 60, 90]" :page-size="params.count"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- <div class="div">财务处理</div> -->
    <!-- 财务处理弹窗 -->
    <MallAccountingHeader ref="mallAccountingHeader" @AccountsGet="AccountsGet">
    </MallAccountingHeader>
    <!-- 新建弹窗 -->
    <AccountsAdd ref="accountsAdd"> </AccountsAdd>
    <!-- 详情弹窗 -->
    <Details ref="details"></Details>
  </div>
</template>
<script>
export default {
  components: {
    VolForm: () => import("@/components/basic/VolForm.vue"),
    VolHeader: () => import("@/components/basic/VolHeader.vue"),
    VolTable: () => import("@/components/basic/VolTable.vue"),
    AccountsAdd: () => import("@/extension/mall/account/accountsAdd.vue"),
    MallAccountingHeader: () =>
      import("@/extension/mall/account/mall_accountingHeader.vue"),
    Details: () => import("@/extension/mall/account/AccountsMain/details.vue"),
  },
  data() {
    // balance_credit 授信余额
    // balance_recharge 充值余额
    // balance_total 总余额
    return {
      tableHeight: 768,
      height: 0, //表格高度
      searchBoxShow: false, //查询弹窗显隐
      loading: false, // 加载
      ck: false,
      //  分页
      currentPage: 1, // 当前页数
      total: 0, // 总条数
      // 用户信息
      user: {},
      //查询条件
      params: {
        accName: "", //应收账户名称
        accCode: "", //应收账户编号
        customer: "", //联系人姓名
        phone: "", //联系人电话
        isvalid: null, //是否有效状态

        // is_delete: 0, //后端要求必传
        start: 0, //起始数据下标
        count: 30, //每页条数
      },
      // 列表数据
      tableData: [],
      columns: [
        {
          field: "account_name",
          title: "应收账户名称",
          type: "string",
          width: 120,
          require: true,
          fixed: "left",
          align: "center",
          sortable: true,
        },
        {
          field: "account_alias",
          title: "应收账户编号",
          type: "string",
          width: 150,
          require: true,
          align: "center",
          sortable: true,
        },

        {
          field: "balance_credit",
          title: "授信余额",
          type: "string",
          width: 100,
          require: true,
          align: "center",

          sortable: true,
        },
        {
          field: "balance_recharge",
          title: "充值余额",
          type: "string",
          width: 100,
          require: true,
          align: "center",
          sortable: true,
        },
        {
          field: "balance_total",
          title: "可用余额",
          type: "string",
          width: 100,
          require: true,
          align: "center",
          sortable: true,
        },
        {
          field: "creator",
          title: "创建人",
          type: "string",
          width: 120,
          align: "center",
        },
        {
          field: "createDate",
          title: "创建时间",
          type: "datetime",
          width: 160,
          align: "center",
          sortable: true,
        },
        {
          field: "createID",
          title: "创建人ID",
          type: "int",
          width: 120,
          hidden: true,
          align: "center",
        },
        {
          field: "modifier",
          title: "修改人",
          type: "string",
          width: 120,
          align: "center",
        },
        {
          field: "modifyDate",
          title: "修改时间",
          type: "datetime",
          width: 160,
          align: "center",
          sortable: true,
        },
        {
          field: "modifyID",
          title: "修改人ID",
          type: "int",
          width: 120,
          hidden: true,
          align: "center",
        },
        {
          field: "is_delete",
          title: "逻辑删除标志",
          type: "int",
          width: 120,
          hidden: true,
          align: "center",
        },
        {
          field: "contact",
          title: "联系人",
          type: "string",
          width: 120,
          require: true,
          align: "center",
        },
        {
          field: "contact_phone",
          title: "联系人电话",
          type: "string",
          width: 120,
          require: true,
          align: "center",
        },
        {
          field: "is_valid",
          title: "是否有效",
          type: "int",
          width: 80,
          require: true,
          align: "center",
          bind: {
            key: "audit",
            data: [
              { key: 0, value: "否" },
              { key: 1, value: "是" },
            ],
          },
        },
        {
          field: "is_autostop",
          title: "是否自动停用",
          type: "int",
          width: 100,
          require: true,
          align: "center",
          bind: {
            key: "audit",
            data: [
              { key: 0, value: "否" },
              { key: 1, value: "是" },
            ],
          },
        },
        {
          field: "effec_startdate",
          title: "起始时间",
          type: "datetime",
          width: 160,
          require: true,
          align: "center",
          sortable: true,
        },
        {
          field: "effec_enddate",
          title: "终止时间",
          type: "datetime",
          width: 160,
          require: true,
          align: "center",
          sortable: true,
        },
        {
          field: "is_entryaccount",
          title: "是否入账",
          type: "int",
          width: 80,
          require: true,
          align: "center",
          bind: {
            key: "audit",
            data: [
              { key: 0, value: "否" },
              { key: 1, value: "是" },
            ],
          },
        },
        {
          field: "temporary_limit",
          title: "临时限额",
          type: "string",
          width: 120,
          require: true,
          align: "center",
        },
        {
          field: "warn_phone",
          title: "警告手机",
          type: "string",
          width: 120,
          require: true,
          align: "center",
        },
        {
          field: "warn_limit",
          title: "警告限额",
          type: "decimal",
          width: 120,
          require: true,
          align: "center",
        },
        {
          field: "account_limit",
          title: "单笔挂账限额",
          type: "decimal",
          width: 120,
          require: true,
          align: "center",
        },
        {
          field: "is_credit",
          title: "是否授信",
          type: "int",
          width: 80,
          require: true,
          align: "center",
          bind: {
            key: "audit",
            data: [
              { key: 0, value: "否" },
              { key: 1, value: "是" },
            ],
          },
        },
        {
          field: "credit_total",
          title: "授信额度",
          type: "decimal",
          width: 120,
          require: true,
          align: "center",
        },
        {
          field: "notes",
          title: "备注",
          type: "string",
          width: 120,
          require: true,
          align: "center",
        },
        {
          field: "account_code_fk",
          title: "应收账户编号",
          type: "string",
          width: 120,
          hidden: true,
          readonly: true,
          require: true,
          align: "center",
        },
        {
          title: "操作",
          fixed: "right",
          type: "string",
          width: 140,
          align: "center",
          render: (h, { row, column, index }) => {
            return h("div", { style: {} }, [
              h(
                "a",
                {
                  props: {},
                  style: {},
                  on: {
                    click: (e) => {
                      this.$refs.mallAccountingHeader.open(row);

                      //this.$Message.info(row.accountsReceivable);
                      // e.stopPropagation()
                      //console.log(this.$refs.gridHeader)
                      //   this.$refs.gridHeader.open(row);
                    },
                  },
                },
                "财务处理  "
              ),
              h(
                "a",
                {
                  props: {},
                  style: {},
                  on: {
                    click: (e) => {
                      console.log("bianji", row);
                      this.$refs.accountsAdd.open();
                      this.$refs.accountsAdd.formFileds.is_delete =
                        row.is_delete;
                      this.$refs.accountsAdd.formFileds.account_code_fk =
                        row.account_code_fk;
                      this.$refs.accountsAdd.formFileds.account_name =
                        row.account_name;
                      this.$refs.accountsAdd.formFileds.is_entryaccount =
                        row.is_entryaccount;
                      this.$refs.accountsAdd.formFileds.is_credit =
                        row.is_credit;
                      this.$refs.accountsAdd.formFileds.credit_total =
                        row.credit_total;
                      this.$refs.accountsAdd.formFileds.account_limit =
                        row.account_limit == null ? '' : row.account_limit;
                      this.$refs.accountsAdd.formFileds.warn_phone =
                        row.warn_phone;
                      if (row.warn_limit) {
                        this.$refs.accountsAdd.formFileds.is_warn = 1;
                      } else {
                        this.$refs.accountsAdd.formFileds.is_warn = 0;
                      }
                      this.$refs.accountsAdd.formFileds.warn_limit =
                        row.warn_limit;

                      this.$refs.accountsAdd.formFileds.temporary_limit =
                      row.temporary_limit == null ? '' : row.temporary_limit;
                      this.$refs.accountsAdd.formFileds.is_valid = row.is_valid;
                      this.$refs.accountsAdd.formFileds.is_autostop =
                        row.is_autostop;
                      let list = [row.effec_startdate, row.effec_enddate];
                      this.$refs.accountsAdd.formFileds.date = list;
                      this.$refs.accountsAdd.formFileds.contact = row.contact;
                      this.$refs.accountsAdd.formFileds.contact_phone =
                        row.contact_phone;
                      this.$refs.accountsAdd.formFileds.account_alias =
                        row.account_alias;
                      this.$refs.accountsAdd.formFileds.notes = row.notes;
                      this.$refs.accountsAdd.formFileds.modifier =
                        this.user.userName;
                      this.$refs.accountsAdd.isAlias = false;
                      this.$refs.accountsAdd.alias = row.account_alias;
                    },
                  },
                },
                "编辑  "
              ),
              h(
                "a",
                {
                  props: {},
                  style: {},
                  on: {
                    click: (e) => {
                      this.$refs.details.open(1);
                      this.$refs.details.formFileds.is_delete = row.is_delete;
                      this.$refs.details.formFileds.account_code_fk =
                        row.account_code_fk;
                      this.$refs.details.formFileds.account_name =
                        row.account_name;
                      this.$refs.details.formFileds.is_entryaccount =
                        row.is_entryaccount;
                      this.$refs.details.formFileds.is_credit = row.is_credit;
                      this.$refs.details.formFileds.credit_total =
                        row.credit_total;
                      this.$refs.details.formFileds.account_limit =
                        row.account_limit;
                      this.$refs.details.formFileds.warn_phone = row.warn_phone;
                      if (row.warn_limit) {
                        this.$refs.details.formFileds.is_warn = 1;
                      } else {
                        this.$refs.details.formFileds.is_warn = 0;
                      }
                      this.$refs.details.formFileds.warn_limit = row.warn_limit;

                      this.$refs.details.formFileds.temporary_limit =
                        row.temporary_limit;
                      this.$refs.details.formFileds.is_valid = row.is_valid;
                      this.$refs.details.formFileds.is_autostop =
                        row.is_autostop;

                      this.$refs.details.formFileds.date =
                        row.effec_startdate + "至" + row.effec_enddate;
                      this.$refs.details.formFileds.contact = row.contact;
                      this.$refs.details.formFileds.contact_phone =
                        row.contact_phone;
                      this.$refs.details.formFileds.finance_notes =
                        row.finance_notes;
                      this.$refs.details.formFileds.notes = row.notes;
                      this.$refs.details.formFileds.modifier =
                        this.user.userName;
                      this.$refs.details.formFileds.account_alias =
                        row.account_alias;
                    },
                  },
                },
                "详情"
              ),
            ]);
          },
        },
      ],
      //  图
      items: [],
    };
  },
  created() {
    this.AccountsGet();
    if (sessionStorage.getItem("user")) {
      this.user = JSON.parse(sessionStorage.getItem("user"));
    }
    // this.$nextTick(() => {
    //   let height = document.getElementsByClassName("abc")[0].offsetHeight;
    //   let paginatHeight =
    //     document.getElementsByClassName("paginat")[0].offsetHeight;
    //   this.height = height - paginatHeight;
    //   console.log("abc", height, paginatHeight, this.height);
    // });
    // 图
    // this.matrixDiagram();
    this.getTableMaxHeight();
  },
  mounted() {
    //获取容器当前高度，重设表格的最大高度
    this.getTableMaxHeight();
    let _this = this;
    window.onresize = function () {
      //用于使表格高度自适应的方法
      _this.getTableMaxHeight(); //获取容器当前高度，重设表格的最大高度
    };
  },
  methods: {
    // 导出
    ExportCampsPeopleBatcl() {
      const o = { order: "dec", page: 1, rows: 99999, sort: "createDate", wheres: [], }
      const c = JSON.parse(JSON.stringify(this.params))
      delete c.count
      delete c.start
      const a = []
      const b = {accName:'account_name',accCode:'account_code_fk',customer:'contact',isvalid:'is_valid',phone:'contact_phone'}
      for(let kay in c){
        if(this.params[kay]){
          a.push({"name":b[kay],"value":c[kay],"displayType": b[kay] =='contact' ? "like" : "select"})
        }
      }
      o.wheres = JSON.stringify(a)
      this.http.post("api/V_accountsmain/Export",o).then((res) => {
          let xmlResquest = new XMLHttpRequest();
          xmlResquest.open(
            "GET",
            this.http.ipAddress + "api/V_accountsmain/DownLoadFile?path=" +
              res.data,
            true
          );
          xmlResquest.setRequestHeader("Content-type", "application/json");
          xmlResquest.setRequestHeader(
            "Authorization",
            this.$store.getters.getToken()
          );
          xmlResquest.responseType = "blob";
          xmlResquest.onload = function (oEvent) {
            if (xmlResquest.status != 200) {
              this.$error("下载文件出错了..");
              return;
            }
            let content = xmlResquest.response;
            let elink = document.createElement("a");
            elink.download = "应收帐户.xlsx";
            let blob = new Blob([content]);
            elink.href = URL.createObjectURL(blob);
            elink.click();
          };
          xmlResquest.send();
        });
     
    },
    getTableMaxHeight() {
      this.$nextTick(function () {
        let box = document.querySelector(".content").attributes;
        let box_clientHeight = box[0].ownerElement.clientHeight;
        console.log(box_clientHeight);
        this.tableHeight = box_clientHeight + 50;
      });
    },
    // 列表接口
    AccountsGet() {
      this.loading = true;
      this.http
        .post("api/AccountsMain/AccountsGet", this.params, false)
        .then((res) => {
          if (!res.status) {
            this.$message.error("请求失败");
            this.loading = false;
            return;
          }
          this.tableData = [];
          if (res.data.accounts.length > 0) {
            res.data.accounts.forEach((item) => {
              if (item.accoBalance) {
                this.$set(
                  item.accMain,
                  "balance_credit",
                  item.accoBalance.balance_credit
                );
                this.$set(
                  item.accMain,
                  "balance_recharge",
                  item.accoBalance.balance_recharge
                );
                this.$set(
                  item.accMain,
                  "balance_total",
                  item.accoBalance.balance_total
                );
              }
              this.tableData.push(item.accMain);
            });
          }
          this.total = res.data.recordCount;
          this.loading = false;
          this.searchBoxShow = false;
        })
        .catch(() => {
          this.loading = false;
          this.searchBoxShow = false;
        });
    },

    // 查询按钮
    searchClick() {
      this.params.start = 0;
      this.params.count = 30;
      this.AccountsGet();
    },
    // 更多按钮
    moreClick() {
      this.searchBoxShow = this.searchBoxShow ? false : true;
    },

    rowClick({ row, column, event }) {
      // this.$refs.table.$refs.table.clearSelection();//清除当前选中的行

      this.$refs.table.$refs.table.toggleRowSelection(row);
    },
    // 刷新按钮
    refreshClick() {
      this.params = {
        accName: "", //应收账户名称
        accCode: "", //应收账户编号
        customer: "", //联系人姓名
        phone: "", //联系人电话
        isvalid: null, //是否有效状态（还没有）

        start: 0, //起始数据下标
        count: 30, //每页条数
      };
      this.AccountsGet();
      this.getTableMaxHeight();
    },
    // 新建按钮
    addClick() {
      this.$refs.accountsAdd.open(0);
      this.$refs.accountsAdd.formReset();
      this.$refs.accountsAdd.formFileds.creator = this.user.userName;
      this.$refs.accountsAdd.formFileds.account_code_fk = "";
      this.$refs.accountsAdd.alias = null;
    },
    // 删除按钮
    deleteClick() {
      let rows = this.$refs.table.getSelected();
      // let idList = [];
      if (rows.length <= 0) return this.$Message.error("请选择要删除的行!");
      if (rows.length > 1) return this.$Message.error("只能删除单条数据!");

      // rows.forEach((item) => {
      //   idList.push(item.account_code_fk);
      // });
      this.http
        .post("api/DistributorNews/getPageData", {
          order: "desc",
          page: 1,
          rows: 30,
          sort: "createDate",
          wheres: `[{\"name\":\"accountsId\",\"value\":\"${rows[0].account_code_fk}\",\"displayType\":\"checkbox\"}]`,
        })
        .then((res) => {
          if (res.rows.length != 0) {
            this.$message({
              type: "error",
              message: "当前数据不能删除!",
            });
          } else {
            this.$confirm("确定要删除选择的数据吗?", "删除警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              // 删除接口
              this.http
                .post(
                  "/api/AccountsMain/AccountsDel",
                  { accid: rows[0].account_code_fk },
                  true
                )
                .then((x) => {
                  console.log("kk", x);
                  if (!x.status) {
                    this.loading = false;
                    this.$message.error(x.message);
                    return;
                  }
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  this.model = false;
                  this.loading = false;
                  this.resetSearch();
                });
            });
          }
        });
    },
    // 重置按钮
    resetSearch() {
      this.params = {
        accName: "", //应收账户名称
        accCode: "", //应收账户编号
        customer: "", //联系人姓名
        phone: "", //联系人电话
        isvalid: null, //是否有效状态

        start: 0, //起始数据下标
        count: 30, //每页条数
      };
      this.AccountsGet();
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.params = {
        start: 0,
        count: val,
      };
      this.AccountsGet();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.start = (val - 1) * this.params.count;
      this.AccountsGet();
    },
    // 矩阵图
    matrixDiagram() {
      // 行
      let num = 10;

      // 列
      let num2 = 5;

      let item = [];
      let row = 1;
      let coll = 1;
      for (let index = 0; index < num * num2; index++) {
        let ele = {
          row: 1,
          coll: 1,
          name: null,
          num: null,
        };
        ele.num = index + 1;

        if (ele.num % num != 0) {
          ele.row = row;
          ele.coll = coll;
          coll = coll + 1;
          item.push(ele);
          console.log("kkk", ele);
        } else {
          ele.row = row;
          row = row + 1;
          ele.coll = coll;
          item.push(ele);
          this.items.push(item);
          console.log("kkk1", this.items);
          coll = 1;
          item = [];
        }
      }
    },
    kankan(num) {
      console.log("kanakn", num);
      this.items.forEach((item) => {
        item.forEach((ele) => {
          if (ele.num == num) {
            if (ele.name) {
              ele.name = false;
            } else {
              ele.name = true;
            }
            return;
          }
        });
      });
    },
  },
};
</script>

<style lang="less">
.search_box {
  .el-form-item__label {
    font-size: 12px;
    color: #939394;
  }
}
</style>

<style lang="less" scoped>
.div {
  width: 360px;
  text-align: center;
  line-height: 50px;
  background-image: linear-gradient(
    to right bottom,
    #edb35d,
    #006fe4,
    #86cd62f5
  );
}
.v-header {
  border: none !important;
  margin-bottom: 11px;
}
.accounts {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  .accounts_header {
    display: flex;
    align-items: center;

    .el-input {
      flex: 1;
      margin: 0 20px 0 80px;
      height: 32px;
    }
    button {
      margin-left: 10px;
    }
    .search_left {
      border-top-right-radius: 0px;
      border-bottom-right-radius: 0px;
    }
    .search_right {
      margin-left: 0px;
      padding-left: 0px;
      padding-right: 5px;
      border-bottom-left-radius: 0px;
      border-left: 1px solid #eee;
      border-top-left-radius: 0;
    }
  }
  .accounts_table {
    position: relative;
    height: 100%;
    .search_box {
      background: #fefefe;
      border: 1px solid #ececec;
      position: absolute;
      z-index: 999;
      left: 15px;
      right: 15px;
      padding: 25px 20px;
      padding-bottom: 0;
      -webkit-box-shadow: 0 7px 18px -12px #bdc0bb;
      box-shadow: 0 7px 18px -12px #bdc0bb;
      .search_form {
        display: flex;
        .el-form-item {
          flex: 1;
          .el-select {
            width: 100%;
          }
        }
      }
      .search_btn {
        text-align: right;
        padding-bottom: 24px;
        button {
          margin-left: 10px;
        }
      }
    }
  }
  .paginat {
    text-align: right;
    padding: 2px 28px;
    border: 1px solid #eee;
    border-top: 0px;
    margin-bottom: 15px;
    box-sizing: border-box;
  }
  .content {
    width: 100%;
    height: calc(100% - 3rem);
  }
}
</style>
